import { collectArticle } from '@/services/articles';
import { createArticleCollectRecordFile, findArticleCollectRecordFile } from '@/services/user';
import useRequest from '@ahooksjs/use-request';
import { PlusCircleFilled } from '@ant-design/icons';
import { ModalForm, ProFormSwitch, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { Button, message } from 'antd';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import styles from './index.less';

interface PropsType {
  refInstance: any;
  articleId: number;
  backHandler?: () => void;
}

const Index: React.FC<PropsType> = (props) => {
  const { refInstance, articleId, backHandler } = props;
  const [collectModalOpen, setCollectModalOpen] = useState<boolean>(false);
  const [collectList, setCollectList] = useState<USER.ArticleCollectT[]>([]);
  const [collectModalStep, setCollectModalStep] = useState<number>(0);
  // 获取收藏夹列表
  const { run: findArticleCollectRecordFileRun } = useRequest(findArticleCollectRecordFile, {
    manual: true,
    onSuccess(res) {
      const { code, message: errorMessage, data = [] } = res;
      if (code === 200) {
        setCollectList(data);
      } else {
        message.error(errorMessage);
      }
    },
  });
  // 改变收藏状态
  const { run: collectArticleRun, loading: collectArticleLoading } = useRequest(collectArticle, {
    manual: true,
    onSuccess(res) {
      const { code, message: errorMessage } = res;
      if (code === 200) {
        findArticleCollectRecordFileRun();
        if (typeof backHandler === 'function') {
          backHandler();
        }
      } else {
        message.error(errorMessage);
      }
    },
  });

  useEffect(() => {
    if (collectModalOpen) {
      findArticleCollectRecordFileRun();
      setCollectModalStep(0);
    }
  }, [collectModalOpen]);
  useImperativeHandle(refInstance, () => ({
    setCollectModalOpen,
  }));
  return (
    <ModalForm<USERAPI.CreateArticleCollectT>
      modalProps={{
        destroyOnClose: true,
      }}
      onOpenChange={setCollectModalOpen}
      layout="horizontal"
      className={styles.collectModalWrapper}
      width="650px"
      open={collectModalOpen}
      title="添加到收藏夹"
      submitter={{
        render: (submitterProps: any) => {
          if (collectModalStep === 0) {
            return null;
          }
          return [
            <Button
              key="back"
              onClick={() => {
                setCollectModalStep(0);
              }}
            >
              返回
            </Button>,
            <Button
              loading={submitterProps?.submitButtonProps?.loading}
              type="primary"
              key="ok"
              onClick={() => {
                submitterProps.submit();
              }}
            >
              确认创建
            </Button>,
          ];
        },
      }}
      onFinish={async (values) => {
        values.privateFlag = values.privateFlag ? 1 : 0;
        const { code, message: errorMessage } = await createArticleCollectRecordFile(values);
        if (code === 200) {
          message.success('创建成功');
          findArticleCollectRecordFileRun();
          setCollectModalStep(0);
        } else {
          message.error(errorMessage);
        }
        return true;
      }}
    >
      {collectModalStep === 0 ? (
        <div className={styles.stepOneWrapper}>
          <Button
            type="primary"
            block
            icon={<PlusCircleFilled />}
            onClick={() => setCollectModalStep(1)}
          >
            创建收藏夹
          </Button>
          <div className={styles.collectListWrapper}>
            {collectList.map((item) => {
              return (
                <div className={styles.item} key={item.articleCollectRecordFileId}>
                  <div className={styles.left}>
                    <div className={styles.title}>{item.articleCollectRecordFileName}</div>
                    <div className={styles.attribute}>{item.collectCount}条内容·私密</div>
                  </div>
                  <Button
                    shape="round"
                    loading={collectArticleLoading}
                    onClick={() => {
                      collectArticleRun({
                        articleCollectRecordFileId: item.articleCollectRecordFileId,
                        articleId,
                      });
                    }}
                  >
                    收藏
                  </Button>
                </div>
              );
            })}
          </div>
        </div>
      ) : (
        <>
          <ProFormText
            formItemProps={{
              rules: [
                { required: true, message: '收藏夹名称必填' },
                { max: 15, message: '名称最大长度为15' },
              ],
            }}
            fieldProps={{ maxLength: 15, showCount: true }}
            name="articleCollectRecordFileName"
            placeholder="收藏夹名称"
          />
          <ProFormTextArea
            fieldProps={{ maxLength: 200, showCount: true }}
            name="description"
            placeholder="收藏夹描述(非必填)"
          />
          <ProFormSwitch
            colon={false}
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 2, offset: 20 }}
            labelAlign="right"
            label="私密"
            tooltip="仅自己可见"
            name="privateFlag"
          />
          <ProFormSwitch
            colon={false}
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 2, offset: 20 }}
            label="默认"
            tooltip="收藏文章是默认的收藏位置"
            name="default"
          />
        </>
      )}
    </ModalForm>
  );
};

export default forwardRef((props: any, ref) => <Index {...props} refInstance={ref} />);
